<script setup>
import axios from "axios";
import { Uploader, Cell, Switch, Divider, Button, Icon, Toast } from "vant";
import { ref } from "vue";

const props = defineProps(["aimDir", "secretKey"]);
const emit = defineEmits(["uploading", "done"]);

let mode = ref(false); //false正常模式，true流畅模式
let fileList = ref([]);
let uploadBtnStatus = ref(false); //true 上传中
let chooseDisable = ref(false);

async function uploadBegin() {
  if (fileList.value.length === 0) {
    Toast("请选择文件");
    return;
  }
  emit("uploading");

  chooseDisable.value = true;
  uploadBtnStatus.value = true;

  let Url =
    import.meta.env.VITE_APP_BASE_URL +
    "/upload?aim=" +
    props["aimDir"] +
    "&key=" +
    props["secretKey"];
    
  for (let i = 0; i < fileList.value.length; i++) {
    fileList.value[i].status = "uploading";
    let res;
    try {
      res = await upload(fileList.value[i].file, Url);
    } catch (err) {
      console.log(err);
      fileList.value[i].status = "failed";
      continue;
    }
    fileList.value[i].status = "done";
  }
  uploadBtnStatus.value = false;
  emit("done");
}

function upload(file, Url) {
  let form = new FormData();
  form.append("file", file);
  return new Promise((resolve, reject) => {
    axios
      .post(Url, form, {
        timeout: 1000,
        headers: {
          "Content-Type": "multipart/form-data",
        },
      })
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err.response);
      });
  });
}
</script>

<template>
  <Cell center value="流畅模式">
    <template #right-icon>
      <Switch v-model="mode" size="24" />
    </template>
  </Cell>
  <Divider />
  <Uploader
    lazy-load
    preview-image
    multiple
    preview-size="62px"
    accept="*"
    v-model="fileList"
    :result-type="mode ? 'file' : 'dataUrl'"
    :disabled="chooseDisable"
  />
  <div class="bottomWrapper">
    <Button
      type="success"
      icon="upgrade"
      loading-text="上传中"
      :loading="uploadBtnStatus"
      @click="uploadBegin"
      >上传</Button
    >
  </div>
</template>
<style scoped>
.bottomWrapper {
  width: 350px;
  position: fixed;
  bottom: 20px;
}
</style>
